package servlets;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import parser.ParserXML;
import businessdelegate.FacadeBusinessDelegate;
import entitiesdto.CantidadMateriaPrimaDTO;
import entitiesdto.StockMateriaPrimaDTO;


 public class EnvioProveedoresSVL extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   
	public EnvioProveedoresSVL() {
		super();
	}   	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}  	

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		String action = (String) request.getParameter("action");
		
		if (action != null && action.equals("LoadXML")){
            this.leerArchivo(request,response);
		}
		if (action !=null && action.equals("GUARDAR ENVIO RECIBIDO")){
			this.guardarEnvioRecibido(request,response);
		}
	}   
	
	public void guardarEnvioRecibido (HttpServletRequest request, HttpServletResponse response){
		
	}
	
	public void leerArchivo (HttpServletRequest request, HttpServletResponse response)
	{
		HttpSession session = request.getSession(true);
		String path = request.getParameter("patharchivo");
		
		List<StockMateriaPrimaDTO> cmpList = new ArrayList<StockMateriaPrimaDTO>();
		
		if (path != null) {
			ParserXML parser = new ParserXML();
			File archivo = new File(path);
			cmpList = parser.recibirEnvioProveedores(archivo);
			if (cmpList != null) {
					try {
						FacadeBusinessDelegate.getInstance().recibirProvedores(cmpList);
					} catch (NamingException e) {
						e.printStackTrace();
					}
			}
		}

		session.setAttribute("listaCmpParseada", cmpList);
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("/enviarProveedores.jsp");
		try {
			dispatcher.forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}